package com.yn.club.common.util;

import java.io.Serializable;
import lombok.ToString;
import org.slf4j.MDC;

/**
 * 通用请求响应
 *
 * @author Bing
 * @version 1.0
 **/
@ToString
public class R<T> implements Serializable {

  /**
   * 响应code
   *
   * @mock 0
   */
  private int code;

  /**
   * 提示信息
   *
   * @mock 成功
   */
  private String msg;

  /**
   * 链路追踪Id
   */
  private final String traceId;

  /**
   * 响应数据
   */
  private T data;

  public R() {
    this.traceId = MDC.get("traceId");
  }

  public static <T> R<T> of(int code, String msg) {
    R<T> r = new R<>();
    r.code = code;
    r.msg = msg;
    return r;
  }

  public static <T> R<T> of(Desc desc) {
    R<T> r = new R<>();
    r.code = desc.getCode();
    r.msg = desc.getDesc();
    return r;
  }

  public static <T> R<T> success(String msg) {
    return success(msg, null);
  }

  public static <T> R<T> ok(T data) {
    return success(null, data);
  }

  public static <T> R<T> ok() {
    return success(null, null);
  }


  public static <T> R<T> success(String msg, T data) {
    R<T> r = new R<>();
    r.code = 200;
    r.msg = msg;
    r.data = data;
    return r;
  }

  public static <T> R<T> error(String msg) {
    return error(msg, null);
  }

  public static <T> R<T> error(String msg, T data) {
    R<T> r = new R<>();
    r.code = 500;
    r.msg = msg;
    r.data = data;
    return r;
  }

  public R<T> code(int code) {
    this.code = code;
    return this;
  }

  public R<T> msg(String msg) {
    this.msg = msg;
    return this;
  }

  public R<T> data(T data) {
    this.data = data;
    return this;
  }

  public int getCode() {
    return code;
  }

  public String getMsg() {
    return msg;
  }

  public String getTraceId() {
    return traceId;
  }

  public T getData() {
    return data;
  }

  public boolean getSuccess() {
    return code == 200;
  }

  public interface Desc {

    /**
     * 响应code
     *
     * @return
     */
    int getCode();

    /**
     * 响应code描述
     *
     * @return
     */
    String getDesc();
  }
}
